import { defineComponent } from 'vue';
import { NButton } from 'naive-ui';
import modeler from '@/store/modules/modeler';
import { deployWithBPMNJS } from '@/api/flow/index';
import {taskAttr} from '@/store/modules/taskAttr';
import {processInfo} from '@/store/modules/processInfo';
import { cloneDeep } from 'lodash-es';
import { connectionAttr } from '@/store/modules/connectionAttr';

const Imports = defineComponent({
  name: 'Saving',
  setup() {
    const modelerStore = modeler();

    const depoly = async () => {
      try {
        const modeler = modelerStore.getModeler!;

        if (!modeler) {
          return window.__messageBox.warning('模型加载失败，请刷新重试');
        }

        const { error, xml } = await modeler.saveXML({ format: true, preamble: true });
        const taskAttrStore = taskAttr();
        const connectionAttrStore = connectionAttr()
        const proceInfoStore=processInfo();
        if (error) {
          console.error(error);
        }
        const taskList=cloneDeep(taskAttrStore.tasks);
        for (let i = 0; i < taskList.length; i++) {  
          if (taskList[i].TASK_RUN_AGAIN_REC_PRO === true) {  
            // 修改对象的属性  
            taskList[i].TASK_RUN_AGAIN_REC_PRO = 1;  
            break; // 找到后退出循环  
          }
          else{
            taskList[i].TASK_RUN_AGAIN_REC_PRO = 0;  
          } 
          if (taskList[i].TASK_RUN_DATA_MOD_ALLOW === true) {
            // 修改对象的属性  
            taskList[i].TASK_RUN_DATA_MOD_ALLOW = 1;  
            break; // 找到后退出循环  
          }
          else{
            taskList[i].TASK_RUN_DATA_MOD_ALLOW = 0;  
          }
          if(taskList[i].TASK_RUN_DATA!=""&&taskList[i].TASK_RUN_DATA!=undefined&&taskList[i].TASK_RUN_DATA!=null){
            taskList[i].TASK_RUN_DATA=JSON.stringify(taskList[i].TASK_RUN_DATA);
          }
        } 

        const connectionList = cloneDeep(connectionAttrStore.connections);
        for (let i = 0; i < connectionList.length; i++) {  
          if(connectionList[i].expressBody!=""&&connectionList[i].expressBody!=undefined&&connectionList[i].expressBody!=null){
            connectionList[i].expressBody=JSON.stringify(connectionList[i].expressBody);
          }
        }

        // deployWithBPMNJS({ stringBPMNXml: xml,tasksInfo: taskList, connectionsInfo:connectionList, processInfo:proceInfoStore}).then((res) => {
        //   if (res.error == '200') {
        //     window.__messageBox.success('发布成功');
        //   } else {
        //     window.__messageBox.error('发布失败');
        //   }
        // });
      } catch (e) {
        window.__messageBox.error((e as Error).message || (e as string));
      }
    };

    return () => (
      <span>
        <NButton type="info" secondary onClick={depoly}>
          {'保存并发布'}
        </NButton>
      </span>
    );
  },
});

export default Imports;
